package com.utils;

import com.entity.Code;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.http.HttpServletRequest;


public class JsonUtil {


    //Java转json对象
    public String JavaToJson(Object data){
        Code code1 = new Code();
        String str= JSON.toJSONString(data);
        System.out.println(str);
        return str;

    }


    //json转java对象
    public Code JsonToJava(String data){
        Code code = JSONObject.parseObject(data, Code.class);
        return code;
    }

    public String getIP(HttpServletRequest request){
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip.contains(",")) {
            return ip.split(",")[0];
        } else {
            return ip;
        }
    }
}
